package com.ftg.learn.springbootmq.work.consumer;

import com.alibaba.fastjson2.JSON;
import com.ftg.learn.springbootmq.work.entity.StudentEntity;
import com.ftg.learn.springbootmq.work.mapper.StudentMapper;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 工作队列消息消费者
 */
@Component
@Slf4j
public class MessageConsumer {

    @Resource
    private StudentMapper studentMapper;

    private final MessageConverter messageConverter = new Jackson2JsonMessageConverter();

    /**
     * 处理工作队列消息
     */
    @RabbitListener(queues = "work.queue")
    public void handleMessage(Message messageObj, Channel channel) throws IOException {
        try {
            Map<String, Object> map = (Map<String, Object>) messageConverter.fromMessage(messageObj);
            log.info("接收到消息: {}", map);
            String operator = (String) map.get("operator");

            switch (operator) {
                case "add":
                    StudentEntity stuAdd = JSON.parseObject(JSON.toJSONString(map.get("body")), StudentEntity.class);
                    log.info("添加学生: {}", stuAdd);
                    studentMapper.insert(stuAdd);
                    break;
                case "update":
                    StudentEntity stuUpdate = JSON.parseObject(JSON.toJSONString(map.get("body")), StudentEntity.class);
                    studentMapper.updateById(stuUpdate);
                    break;
                case "delete":
                    String id = map.get("body").toString();
                    studentMapper.deleteById(id);
                    break;
                default:
                    log.warn("未知操作类型: {}", operator);
            }
            
            // 正确地确认消息
            channel.basicAck(messageObj.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理消息时发生异常", e);
            // 发生异常时，确认消息，避免重复处理
            channel.basicAck(messageObj.getMessageProperties().getDeliveryTag(), false);
        }
    }
}